package base;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import util.core.EditorDocumentUtils;

/**
 * 写入数据类的action
 */

public abstract class WriteTextAction extends AnAction {

    /**
     * 插入的数据内容
     * @param anActionEvent
     * @param caret 光标
     * @param selection 被选中的文字 可能为空
     */
    protected abstract String content(AnActionEvent anActionEvent, Caret caret, String selection);

    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
        Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);

        if (project == null || editor == null) {
            return;
        }

        //New instance of Runnable to make a replacement
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (Caret caret : editor.getCaretModel().getAllCarets()) {
                    String selection = EditorDocumentUtils.getSelectionTextWithCaret(caret);
                    EditorDocumentUtils.insertTextAtCaret(caret, content(anActionEvent, caret, selection));
                }
            }
        };

        //Making the replacement
        WriteCommandAction.runWriteCommandAction(project, runnable);
    }

}
